package com.geneqiao.jdbc.pool;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;

public class JDBCConn
{

	private static final Logger logger = Logger.getLogger(JDBCConn.class);

	private long start;
	private Connection conn;

	public JDBCConn(Connection connection, Boolean isNew)
	{
		this.start = System.currentTimeMillis();
		this.conn = connection;
		if (logger.isDebugEnabled())
		{
			if (isNew)
				logger.debug("Put a new connection");
			else
				logger.debug("Release an old connection");
		}
	}

	public Connection getConnection()
	{
		return conn;
	}

	public long getNotUsedTime()
	{
		return System.currentTimeMillis() - start;
	}

	public void close()
	{
		try
		{
			if(this.conn != null && !this.conn.isClosed())
				this.conn.close();
			this.conn = null;
		}
		catch (Exception e)
		{
			logger.error("关闭链接失败", e);
		}
	}

	public boolean isValid()
	{
		if(this.conn == null)
			return false;
		try
		{
			return this.conn.isValid(0);
		}
		catch (SQLException e)
		{
			logger.error("判断链接是否有效失败", e);
			return false;
		}
	}

}
